package com.leyou.item.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.conditions.query.QueryChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.leyou.common.dto.PageDTO;
import com.leyou.common.exception.LyException;
import com.leyou.common.utils.RedisConstant;
import com.leyou.item.dto.BrandDTO;
import com.leyou.item.entity.Brand;
import com.leyou.item.entity.CategoryBrand;
import com.leyou.item.mapper.BrandMapper;
import com.leyou.item.service.BrandService;
import com.leyou.item.service.CategoryBrandService;
import com.leyou.item.service.CategoryService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class BrandServiceImpl extends ServiceImpl<BrandMapper, Brand> implements BrandService {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private CategoryBrandService categoryBrandService;

    @Override
    public PageDTO<BrandDTO> queryBrandByPage(Integer currentPage, Integer pageSize, String wrapper) {

        // 1.分页信息的健壮性处理
        currentPage = Math.min(currentPage,100);
        // 最多显示100页，每页最少显示5条
        pageSize = Math.max(pageSize,5);

        // 2.分页查询，自动回填结果数据
        Page<Brand> pageInfo = new Page<>(currentPage, pageSize);

        // 3.判断分页条件wrapper是否存在
        boolean isWrapperExists = StringUtils.isNoneBlank(wrapper);
        // 4.如果wrapper存在，添加like和eq的查询条件，否则不添加
        query().like(isWrapperExists,"name",wrapper)
                .or()
                .eq(isWrapperExists,"letter",wrapper)
                .page(pageInfo);
        // 5.封装结果
        List<Brand> records = pageInfo.getRecords();

        return new PageDTO<>(pageInfo.getTotal(),pageInfo.getPages(),BrandDTO.convertEntityList(records));
    }

    @Override
    @Transactional
    public void saveBrand(BrandDTO brandDTO) {

        Brand brand = brandDTO.toEntity(Brand.class);
        // 保存brand
        this.save(brand);

//        // 获取分类id
//        List<Long> categoryIds = brandDTO.getCategoryIds();
//
//        Long brandId = brand.getId();
//
//        // 封装中间表对象集合
//        List<CategoryBrand> categoryBrands = new ArrayList<>();
//
//        for (Long categoryId : categoryIds) {
//
//            // 创建中间表对象
//            CategoryBrand categoryBrand = CategoryBrand.of(categoryId, brandId);
//
//            categoryBrands.add(categoryBrand);
//
//        }
        // 封装中间表对象集合
//        List<CategoryBrand> categoryBrands = brandDTO
//                .getCategoryIds()
//                .stream()
//                .map(id -> CategoryBrand.of(id,/*brandDTO.toEntity(Brand.class).getId()*/brand.getId()))
//                .collect(Collectors.toList());
//        // 4.批量写入中间表数据
//        categoryBrandService.saveBatch(categoryBrands);
        saveCategoryBrand(brandDTO.getCategoryIds(), brand.getId());

        if (!StringUtils.isBlank(brand.getImage())) {

            redisTemplate.opsForSet().add(RedisConstant.BRAND_PIC_DB_RESOURCES,brand.getImage());

        }

    }

    private void saveCategoryBrand(List<Long> categoryIds, Long cid) {
        List<CategoryBrand> categoryBrands = categoryIds
                .stream()
                .map(id -> CategoryBrand.of(id,cid))
                .collect(Collectors.toList());
        // 批量写入中间表数据
        categoryBrandService.saveBatch(categoryBrands);
    }

    @Override
    @Transactional
    public void updateBrand(BrandDTO brandDTO) {

        // 1.更新品牌
        boolean flag = this.updateById(brandDTO.toEntity(Brand.class));

        if (!flag) {
            // 更新失败，抛出异常
            throw new LyException(HttpStatus.INTERNAL_SERVER_ERROR.value(),"更新品牌失败！");

        }

        //List<CategoryBrand> brand_id = categoryBrandService.query().eq("brand_id", brandDTO.getId()).list();

        // 2.根据品牌id删除中间表数据
        flag = categoryBrandService.remove(new QueryWrapper<CategoryBrand>().eq("brand_id", brandDTO.getId()));

        if (!flag) {

            throw new LyException(HttpStatus.INTERNAL_SERVER_ERROR.value(),"更新品牌失败，删除中间表数据出错");

        }

        /*
 3.插入中间表数据
        List<CategoryBrand> categoryBrands = brandDTO
                .getCategoryIds()
                .stream()
                .map(id -> CategoryBrand.of(id,/*brandDTO.toEntity(Brand.class).getId()* /brandDTO.getId()))
                .collect(Collectors.toList());
        // 4.批量写入中间表数据
        categoryBrandService.saveBatch(categoryBrands);
*/

        saveCategoryBrand(brandDTO.getCategoryIds(), brandDTO.getId());

    }

    @Override
    @Transactional
    public void deleteById(Long id) {

        //TODO 什么样的品牌才能被删除，不满足条件的一定不能删除（有人用，从表中的数据被主表引用了）

        // 1.删除品牌表中的数据
        this.removeById(id);

        // 2.根据id删除中间表数据信息
        categoryBrandService.remove(new QueryWrapper<CategoryBrand>().eq("brand_id",id));

    }

}
